<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--分类数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="itemTypeName" placeholder="请输入分类名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="itemTypeOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" default-expand-all @node-click="handleNodeClick" />
        </div>
      </el-col>
      <!--物料数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
          label-width="68px">
          <el-form-item label="物料编码" prop="itemCode">
            <el-input v-model="queryParams.itemCode" placeholder="请输入物料编码" clearable style="width: 240px"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="物料名称" prop="itemName">
            <el-input v-model="queryParams.itemName" placeholder="请输入物料名称" clearable style="width: 240px"
              @keyup.enter.native="handleQuery" />
          </el-form-item>

          <el-form-item label="物料阶段状态" prop="phaseCode" label-width="120px">
            <el-select v-model="queryParams.phaseCode"
                       placeholder="物料阶段状态">
              <el-option
                  v-for="dict in dict.type.md_phase_code"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="一码多料类型" prop="multiFlag" label-width="120px">
            <el-select v-model="queryParams.multiFlag"
                       placeholder="一码多料类型">
              <el-option
                  v-for="dict in dict.type.item_multi_flag"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['mes:md:mditem:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['mes:md:mditem:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['mes:md:mditem:remove']">删除</el-button>
          </el-col>
<!--          <el-col :span="1.5">
            <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
              v-hasPermi="['mes:md:mditem:import']">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['mes:md:mditem:export']">导出</el-button>
          </el-col>-->
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="itemList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="物料编码" width="120" align="center" key="itemCode" prop="itemCode"
            v-if="columns[0].visible">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleView(scope.row)" v-hasPermi="['mes:md:mditem:query']">{{
                scope.row.itemCode }}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" min-width="120" align="left" key="itemName" prop="itemName"
            v-if="columns[1].visible" :show-overflow-tooltip="true" />

          <el-table-column label="一码多料类型" min-width="120" align="left" key="multiFlag" prop="multiFlag"
                           v-if="columns[10].visible" :show-overflow-tooltip="true"  >
              <template slot-scope="scope">
                <dict-tag :options="dict.type.item_multi_flag" :value="scope.row.multiFlag"/>
              </template>
          </el-table-column>
          <el-table-column label="物料图片" align="center" prop="imgUrl" width="100">
            <template slot-scope="scope">
              <image-preview v-if="scope.row.imgUrl" :src="scope.row.imgUrl" :width="50" :height="50"/>
            </template>
          </el-table-column>

          <el-table-column label="规格型号" align="left" key="specification" prop="specification" v-if="columns[2].visible"
            :show-overflow-tooltip="true" />
          <el-table-column label="单位" align="center" key="unitOfMeasure" prop="unitOfMeasure" v-if="columns[3].visible"
            :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ convertUnitmeasure(scope.row.unitOfMeasure) }}
            </template>
          </el-table-column>
          <el-table-column label="物料/产品" align="center" key="itemOrProduct" prop="itemOrProduct"
            v-if="columns[4].visible" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.mes_item_product" :value="scope.row.itemOrProduct" />
            </template>
          </el-table-column>

          <el-table-column label="所属分类" align="center" key="itemTypeName" prop="itemTypeName" v-if="columns[5].visible"
            width="110" />
          <el-table-column label="是否启用" align="center" key="enableFlag" v-if="columns[6].visible">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.enableFlag" />
            </template>
          </el-table-column>
          <el-table-column label="设置安全库存" align="center" key="safeStockFlag" v-if="columns[7].visible"  width="130">
            <template slot-scope="scope"  >
              <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.safeStockFlag" />
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[8].visible" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料阶段状态" align="center" prop="phaseCode" v-if="columns[9].visible" width="160">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.md_phase_code" :value="scope.row.phaseCode"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['mes:md:mditem:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['mes:md:mditem:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 添加或修改物料产品编码对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="物料编码" prop="itemCode">
<!--              <el-input v-model="form.itemCode" readonly="readonly" maxlength="64" v-if="optType == 'view'" />-->
              <el-input v-model="form.itemCode" placeholder="请输入物料编码" maxlength="64" :disabled="!isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="80">
              <el-switch v-model="autoGenFlag" active-color="#13ce66" active-text="自动生成"
                @change="handleAutoGenChange(autoGenFlag)" v-if="optType != 'view'">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="itemName">
<!--              <el-input v-model="form.itemName" maxlength="500" readonly="readonly" v-if="optType == 'view'" />-->
              <el-input v-model="form.itemName" placeholder="请输入物料名称" maxlength="500" :disabled="!isEdit" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" type="textarea" placeholder="请输入规格型号" maxlength="100" :disabled="!isEdit" show-word-limit/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="物料阶段状态" prop="phaseCode">
              <el-select v-model="form.phaseCode"
                         placeholder="--物料阶段状态--"  :disabled="optType == 'view'">
                <el-option
                    v-for="dict in dict.type.md_phase_code"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位" prop="unitOfMeasure">
              <el-select v-model="form.unitOfMeasure" disabled v-if="optType == 'view'">
                <el-option v-for="item in measureOptions" :key="item.measureCode" :label="item.measureName"
                  :value="item.measureCode" :disabled="item.enableFlag == 'N'"></el-option>
              </el-select>

              <el-select v-model="form.unitOfMeasure" placeholder="请选择单位" v-else>
                <el-option v-for="item in measureOptions" :key="item.measureCode" :label="item.measureName"
                  :value="item.measureCode" :disabled="item.enableFlag == 'N'"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料/产品分类" prop="itemTypeId">
              <treeselect v-model="form.itemTypeId" :options="itemTypeOptions" :show-count="true" disabled
                v-if="optType == 'view'" />
              <treeselect v-model="form.itemTypeId" :options="itemTypeOptions" :show-count="true" placeholder="请选择所属分类"
                v-else :disable-branch-nodes="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否启用">
              <el-radio-group v-model="form.enableFlag" disabled v-if="optType == 'view'">
                <el-radio v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.value">{{ dict.label
                  }}</el-radio>
              </el-radio-group>
              <el-radio-group v-model="form.enableFlag" v-else>
                <el-radio v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.value">{{ dict.label
                  }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安全库存">
              <el-radio-group v-model="form.safeStockFlag" disabled v-if="optType == 'view'">
                <el-radio v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.value">{{ dict.label
                  }}</el-radio>
              </el-radio-group>

              <el-radio-group v-model="form.safeStockFlag" v-else>
                <el-radio v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.value">{{ dict.label
                  }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.safeStockFlag == 'Y'">
          <el-col :span="12">
            <el-form-item label="最小库存量">
              <el-input-number v-model="form.minStock" :percision="2" :step="1" disabled v-if="optType == 'view'" />
              <el-input-number v-model="form.minStock" :percision="2" :step="1" placeholder="请输入最小安全库存量" v-else />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大库存量">
              <el-input-number v-model="form.maxStock" :percision="2" :step="1" disabled v-if="optType == 'view'" />
              <el-input-number v-model="form.maxStock" :percision="2" :step="1" placeholder="请输入最大安全库存量" v-else />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="一码多料类型" prop="phaseCode">
              <el-select v-model="form.multiFlag"
                         placeholder="一码多料类型"  :disabled="optType == 'view'">
                <el-option
                    v-for="dict in dict.type.item_multi_flag"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="有效年限" prop="expiryYear">
              <el-input :disabled="!isEdit"
                  v-model="form.expiryYear"
                  onkeyup="value=(value.replace(/\D/g,'')==''?'':parseInt(value))"
                  placeholder="请输入有效年限"
              />
            </el-form-item>

          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="物料图片" prop="imgUrl" label-width="110px">
              <template v-if="isEdit">
                <image-upload v-model="form.imgUrl" :limit="1"  />
              </template>
              <template v-else>
                <img v-if="form.imgUrl" :src="form.imgUrl" id="realBackView1" style="width:40% ;height: 40%;" @click="zoomImage('realBackView1')"/>
              </template>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">
            <el-form-item label="入库仓库">
              <el-cascader v-model="warehouseInfo" :options="warehouseOptions" :props="warehouseProps"
                           :show-all-levels="true"    @change="handleWarehouseChanged">
              </el-cascader>
            </el-form-item>
          </el-col>-->
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="物料规格书" prop="specificationUrl" label-width="110px">
              <template v-if="isEdit">
                <file-upload v-model="form.specificationUrl" :limit="1" placeholder="物料规格书" />
              </template>
              <template v-else>
                <el-link type="primary" href="form.specificationUrl">{{form.specificationUrl}}</el-link>
<!--                <el-input v-model="form.specificationUrl"      placeholder="物料规格书" readonly="readonly"     />-->
              </template>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
<!--              <el-input v-model="form.remark" type="textarea" readonly v-if="optType == 'view'" maxlength="500" show-word-limit ></el-input>-->
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"  :disabled="!isEdit" maxlength="500" show-word-limit   ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template>
        <el-tabs type="border-card" v-if="form.itemId != null">

          <!--单物料-bom管理-->
          <el-tab-pane label="单物料-BOM管理" :disabled="form.multiFlag === 'Y'" v-if="form.multiFlag  == 'N'" >
            <template>
              <el-tabs v-model="editableTabsValue" @tab-click="handleTabClick"
                       @edit="tableEdit"
                       :closable="false"
                       type="border-card" v-if="form.itemId != null">
                <el-button @click="showAddTabDialog" :disabled="!isEdit" >增加BOM版本</el-button>
                <el-tab-pane :ref="`itemBomPane_${index}`"
                             :closable="false"
                             v-for="(item, index) in editableTabs"
                             :key="item.name"
                             :label="item.label"
                             :name="item.name">
                  <ItemBom
                      ref="itemBom"
                      :optType="optType"
                      :itemId="form.itemId"
                      :tabName="item.name"
                      :bomVersion="item.bomVersion"
                      :bomVersionId="item.bomVersionId"
                  ></ItemBom>
                </el-tab-pane>

              </el-tabs>

              <!-- 添加弹窗 -->
              <div>
                <el-dialog
                    title="新增BOM版本"
                    :visible.sync="dialogVisible"
                    width="30%"
                    :before-close="handleClose"
                    append-to-body>
                  <el-input v-model="newBomVersion" placeholder="请输入新的BOM版本号"></el-input>
                  <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addTab(newBomVersion)">确 定</el-button>
                  </span>
                </el-dialog>
              </div>

            </template>

          </el-tab-pane>


          <!--一码多料-->
          <el-tab-pane label="一码多料"   :disabled="form.multiFlag !== 'Y'" v-if="form.multiFlag === 'Y'">
           <ItemTab ref="itemTab"
                    :optType="optType"
                    :itemId="form.itemId"
                    :mainItemId="form.itemId"
            >
           </ItemTab>
          </el-tab-pane>

          <!--供应商 单一物料显示-->
          <el-tab-pane label="物料供应商"    :disabled="form.multiFlag === 'Y'" v-if="form.multiFlag  == 'N'">
            <VendorTab ref="vendorTab"
             :optType="optType"
             :itemId="form.itemId"
            >
            </VendorTab>
          </el-tab-pane>

          <!--仓库 单一物料显示-->
          <el-tab-pane label="仓库"    :disabled="form.multiFlag === 'Y'" v-if="form.multiFlag  == 'N'">
<!--            <VendorTab ref="vendorTab"
                       :optType="optType"
                       :itemId="form.itemId"
            >
            </VendorTab>-->

            <WareHouseTab ref="wareHouseTab"
                          :optType="optType"
                          :itemId="form.itemId">

            </WareHouseTab>
          </el-tab-pane>
        </el-tabs>
      </template>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType == 'view'">返回</el-button>
        <el-button type="primary" @click="submitForm" v-else>保 存</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 物料导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMdItem, getMdItem, delMdItem, addMdItem, updateMdItem } from "@/api/mes/md/mdItem";

import ItemBom from "./components/itembom.vue";
import SOPTab from "./components/sop.vue"
import ItemTab from "./components/item.vue";
import { listAllUnitmeasure } from "@/api/mes/md/unitmeasure";
import { genCode } from "@/api/system/autocode/rule"
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/mes/md/itemtype";
import Treeselect from "@riophae/vue-treeselect";
import { pinyin } from "pinyin-pro";
import { mapGetters } from "vuex";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import VendorTab from "./components/vendor.vue";
import WareHouseTab from "./components/warehouse.vue"
import { addBomVersion} from "@/api/mes/md/bom";
import { getTreeList } from "@/api/mes/wm/warehouse";
export default {
  name: "MdItem",
  dicts: ['sys_yes_no', 'mes_item_product','md_phase_code','item_multi_flag'],
  components: { Treeselect, ItemBom, SOPTab ,ItemTab,VendorTab,WareHouseTab},
  data() {
    return {
      warehouseInfo: [],
      warehouseOptions: [],
      warehouseProps: {
        multiple: true,
        value: 'pId',
        label: 'pName',
        checkStrictly: false
      },

      dialogVisible: false, // 控制弹窗的显示
      newBomVersion: '' ,// 输入框的值
      currentBomVersion: '',
      currentBomVersionId: '',
      editableTabsValue: '',
      editableTabs: [
        // { name: 'tab1', label: 'BOM组成' }
      ],
      isEdit: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料产品表格数据
      itemList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      itemTypeOptions: undefined,
      // 是否显示弹出层
      open: false,
      //弹框的操作类型 view add edit
      optType: undefined,
      // 部门名称
      itemTypeName: undefined,
      //自动生成物料编码标识
      autoGenFlag: false,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {
        bomVersionList:[]
      },
      bomVersionForm:{},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/mes/md/mditem/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemCode: undefined,
        itemName: undefined,
        itemTypeId: 0,
        phaseCode: undefined,
        multiFlag: undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `物料/产品编码`, visible: true },
        { key: 1, label: `物料/产品名称`, visible: true },
        { key: 2, label: `规格型号`, visible: true },
        { key: 3, label: `单位`, visible: true },
        { key: 4, label: `物料/产品`, visible: true },
        { key: 5, label: `物料分类`, visible: true },
        { key: 6, label: `是否启用`, visible: true },
        { key: 7, label: `是否设置安全库存`, visible: true },
        { key: 8, label: `创建时间`, visible: true },
        { key: 9, label: `物料阶段状态`, visible: true },
        { key: 10, label: `一码多料类型`, visible: true }
      ],
      // 表单校验
      rules: {
        itemCode: [
          { required: true, message: "物料/产品编码不能为空", trigger: "blur" },
          { max: 64, message: '物料/产品编码长度必须小于64个字符', trigger: 'blur' }
        ],
        itemName: [
          { required: true, message: "物料/产品名称不能为空", trigger: "blur" }
        ],
        unitOfMeasure: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ],
        itemTypeId: [
          { required: true, message: "物料分类不能为空", trigger: "blur" },
        ],
        phaseCode: [
          { required: true, message: "物料阶段状态不能为空", trigger: "blur" },
        ],
        itemVersion: [
          { required: true, message: "物料版本不能为空", trigger: "blur" },
        ],
        multiFlag: [
          { required: true, message: "一码多料不能为空", trigger: "blur" },
        ]
      }
    };
  },
  computed: {
    ...mapGetters({
      measureOptions: 'unitmeasureList'
    })
    ,
    // 计算属性来获取当前激活的标签页对象，并定义 setter
    currentTab: {
      get() {
        // 确保 editableTabs 不为空
        if (!this.editableTabs || !Array.isArray(this.editableTabs)) {
          return null;
        }
        return this.editableTabs.find(tab => tab.name === this.editableTabsValue);
      },
      set(newValue) {
        // 确保 editableTabs 不为空
        if (!this.editableTabs || !Array.isArray(this.editableTabs)) {
          return;
        }
        const currentTabIndex = this.editableTabs.findIndex(tab => tab.name === this.editableTabsValue);
        if (currentTabIndex !== -1) {
          this.editableTabs[currentTabIndex] = newValue;
        }
      }
    }
  },
  watch: {
    // 根据名称筛选分类树
    itemTypeName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getWarehouseList();
  },

  methods: {
    // currentTab() {
    //   return this.editableTabs.find(tab => tab.name === this.editableTabsValue);
    // },
    //选择默认的仓库、库区、库位
    handleWarehouseChanged(obj) {
      console.log('--handleWarehouseChanged obj--',obj);
      const arr=obj;
      console.log('arr length--',arr.length);
      if (obj != null) {
        this.form.warehouseId = obj[0];
        this.form.locationId = obj[1];
        this.form.areaId = obj[2];
      }
    },
    getWarehouseList() {
      getTreeList().then(response => {
        if (response.data) {
          this.warehouseOptions = response.data.filter((el) => {
            return el.warehouseCode.indexOf('VIR') == -1;
          });;
        }
        this.warehouseOptions.map(w => {
          w.children.map(l => {
            let lstr = JSON.stringify(l.children).replace(/locationId/g, 'lId').replace(/areaId/g, 'pId').replace(/areaName/g, 'pName');
            l.children = JSON.parse(lstr);
          });

          let wstr = JSON.stringify(w.children).replace(/warehouseId/g, 'wId').replace(/locationId/g, 'pId').replace(/locationName/g, 'pName');
          w.children = JSON.parse(wstr);

        });
        let ostr = JSON.stringify(this.warehouseOptions).replace(/warehouseId/g, 'pId').replace(/warehouseName/g, 'pName');
        this.warehouseOptions = JSON.parse(ostr);
      });
    },
    showAddTabDialog() {
      this.dialogVisible = true;
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.dialogVisible = false;
            done();
          })
          .catch(() => {});
    },
    handleTabClick(tab, event) {
      var cTab = this.currentTab;
      this.currentBomVersion=cTab.name;
      this.currentBomVersionId=cTab.bomVersionId;
    },
    // addTab() {
    //   const tabName = `tab${this.editableTabs.length + 1}`;
    //   // this.editableTabs.push({ name: tabName, label: 'BOM组成' });
    //   this.editableTabs.push({
    //     name: tabName,
    //     label: 'BOM组成',
    //     bomVersionId: ''
    //   });
    //   this.editableTabsValue = tabName; // 切换到新增的标签页
    // },
    addTab(version) {

      this.bomVersionForm.bomVersion=version;
      this.bomVersionForm.mdItemId=this.form.itemId;
      console.log('bomVersionForm---',this.bomVersionForm);
      addBomVersion(this.bomVersionForm).then(response => {
        console.log('addTab -response,',response);
        this.$modal.msgSuccess("新增成功");
        // this.getList();
        const newTab = {
          name: response.data.bomVersion,
          label: response.data.bomVersion,
          bomVersion: response.data.bomVersion,
          bomVersionId: response.data.bomVersionId
        };
        this.editableTabs.push(newTab);
        this.editableTabsValue = version; // 设置新tab为当前选中
        this.dialogVisible = false; // 关闭对话框
      });
    },
    tableEdit(tab, event){
      console.log('tableEdit tableName=',tab);
      console.log('tableEdit event=',event);
    },
    removeTab(name) {
      // 从 editableTabs 数组中移除对应项
      this.editableTabs = this.editableTabs.filter(tab => tab.name !== name);
      // 如果移除的是当前激活的标签页，则选择下一个可用的标签页作为当前激活的标签页
      if (this.editableTabsValue === name) {
        if (this.editableTabs.length > 0) {
          this.editableTabsValue = this.editableTabs[0].name;
        } else {
          this.editableTabsValue = '';
        }
      }
    },
    /**
     * 物料名称输入框事件
     */
    itemNameChange(value) {
      this.form.itemCode = pinyin(value, { pattern: 'first' }).toUpperCase().replace(/\s+/g, "");
    },
    /** 查询nnnnn物料编码列表 */
    getList() {
      this.loading = true;
      listMdItem(this.queryParams).then(response => {
        this.itemList = response.rows;
        this.total = response.total;
        this.loading = false;
      }
      );
    },
    /** 查询分类下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.itemTypeOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.itemTypeId = data.id;
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      // console.log('--重置---');
      this.form = {
        itemId: undefined,
        itemTypeId: undefined,
        itemCode: undefined,
        itemName: undefined,
        specification: undefined,
        unitOfMeasrue: undefined,
        itemOrProduct: undefined,
        enableFlag: 'Y',
        safeStockFlag: 'N',
        minStock: 0,
        maxStock: 0,
        optType: undefined,
        remark: undefined,
        imgUrl: '',
        phaseCode: undefined,
        itemVersion: undefined,
        specificationUrl: '',
        multiFlag: 'N',
        expiryYear:undefined

      };
      this.isEdit=true;
      this.autoGenFlag = false;
      this.resetForm("form");
      this.editableTabs = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.itemId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 查询明细按钮操作
    handleView(row) {
      this.reset();
      this.getTreeselect();
      const itemId = row.itemId || this.ids;

      getMdItem(itemId).then(response => {
        this.title = "查看物料/产品";
        this.optType = "view";
        this.open = true;
        this.isEdit=false;

        this.form = response.data.info;
        this.form.bomVersionList=response.data.bomVersionList;
        const bomVersionList=response.data.bomVersionList;
        if(bomVersionList!=null){
          this.initializeTabs(bomVersionList);
        }
        if (this.editableTabs.length > 0) {
          this.editableTabsValue = this.editableTabs[0].name;
        } else {
          this.editableTabsValue = '';
        }
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();
      if (this.queryParams.itemTypeId != 0) {
        this.form.itemTypeId = this.queryParams.itemTypeId;
      }
      this.isEdit=true;
      this.optType = "add";
      this.open = true;
      this.title = "新增物料/产品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      const itemId = row.itemId || this.ids;
      this.isEdit = true;
      // console.log("==handleUpdate==>",this.editableTabs)

      getMdItem(itemId).then(response => {
        // console.log('************** 返回结果',response.data);
        this.form = response.data.info;
        this.form.bomVersionList=response.data.bomVersionList;
        const bomVersionList=response.data.bomVersionList;
        if(bomVersionList!=null){
          this.initializeTabs(bomVersionList);
        }
        if (this.editableTabs.length > 0) {
          this.editableTabsValue = this.editableTabs[0].name;
        } else {
          this.editableTabsValue = '';
        }
        // if(this.editableTabs.length>0){
        //   this.editableTabsValue = this.editableTabs[0].name; // 切换到新增的标签页
        // }

        this.open = true;
        this.optType = "edit";
        this.title = "修改物料/产品";
        this.isEdit=true;
      });
    },
    initializeTabs(bomVersionList) {
    if (bomVersionList != null) {
      let firstTab = null;
      let lastTab = null;
      bomVersionList.forEach((bomVersion, index) => {
        const refName = `itemBomPane_${index}`;
        this.editableTabs.push({
          name: bomVersion.bomVersion,
          label: bomVersion.bomVersion,
          bomVersionId: bomVersion.bomVersionId
        });

        if (index === 0) {
          firstTab = bomVersion.bomVersion;
        }
        lastTab = bomVersion.bomVersion;
      });

      // 设置第一个或最后一个标签页为激活状态
      this.editableTabsValue = firstTab || lastTab;
    }
  },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.itemId != undefined) {
            updateMdItem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMdItem(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const itemIds = row.itemId || this.ids;
      this.$modal.confirm('确认删除数据项？').then(function () {
        return delMdItem(itemIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/md/mditem/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "物料/产品导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('mes/md/mditem/importTemplate', {
      }, `md_item_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    //自动生成物料编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        let codeType = 'ITEM_CODE';
        // 判断当前选择的是否是产品分类,如果是产品分类,生成的code是产品编码
        if (this.isNotEmpty(this.form.itemTypeId) && this.form.itemTypeId === '10000004') {
          codeType = 'PRODUCT_CODE';
        }
        genCode(codeType).then(response => {
          this.form.itemCode = response;
        });
      } else {
        this.form.itemCode = null;
      }
    },
    zoomImage(idName) {
      console.log('父类调用',idName);
      var image = document.getElementById(idName);
      // image.style.width = "100%";
      // image.style.height = "100%";
      if (image.style.width === "100%") {
        // 图片已放大，还原为原始大小
        image.title="点击放大";
        image.style.width = "40%";
        image.style.height = "40%";

      } else {
        image.title="点击缩小";
        // 图片未放大，放大为全屏大小
        image.style.width = "100%";
        image.style.height = "100%";

      }
    }
  }
};
</script>

<style scoped>
.el-dialog__backdrop {
  background-color: rgba(0, 0, 0, 0); /* 完全透明 */
  /* 或者设置较低的透明度，如： */
  /* background-color: rgba(0, 0, 0, 0.1); */
}

/* 确保弹窗本身的位置正确 */
.el-dialog {
  z-index: 10000; /* 确保弹窗位于其他元素之上 */
}

/* 如果需要调整遮罩层的过渡动画 */
.el-dialog__wrapper .el-dialog__container {
  animation: none; /* 移除动画 */
}

/* 确保遮罩层不被其他元素覆盖 */
.el-dialog__backdrop {
  z-index: 9999; /* 确保遮罩层位于弹窗之下 */
}
</style>
